package com.nn.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nn.mapper.UserMapper;
import com.nn.pojo.User;
import com.nn.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        String password = user.getPassword();
        String md5Str = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Str);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(queryWrapper);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return userDB == null ? null : uuid;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult getUserList(PageResult pageResult) {
        IPage iPage = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "username", pageResult.getQuery());
        iPage = userMapper.selectPage(iPage, queryWrapper);
        long total = iPage.getTotal();
        List<User> rows = iPage.getRecords();
        pageResult.setTotal(total).setRows(rows);
        return pageResult;
    }

    @Override
    public void addUser(User user) {
        String password = user.getPassword();
        String md5Str = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Str);
        user.setStatus(true);
        userMapper.insert(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteId(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.selectById(id);

    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }


}
